package com.gxp.common.utils;

import com.gxp.common.core.domain.entity.ExpParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ExpParamsUtils {
    private static final Logger log = LoggerFactory.getLogger(ExpParamsUtils.class);

    //PROTON16
    //acqfrq:11013.215859|acqmode:dqd|acqtime:3.99984896|array:|arraymode:0|console:BIXI-I|cs:0|d1:1.0|deadtime:30.0|
    // decon:nnn|decon1:nnn|decplvl:40.0|decplvl1:40.0|decpw:40.0|decpw1:40.0|dectype:www|dectype1:www|dimension:1|
    // dummyscan:2|fq:0.0|frqb:500.0857556|frqb1:125.7466632|frqo:6.0|frqo1:0.0|frqohz:3000.51|frqohz1:0.0|gain:30.0|
    // lockfreq:76.766209|magnet:AS400|np:44051|ns:16|nuc:H1|nuc1:C13|p1:11.0|plvl1:51.0|predelay:10.0|probe:probehead|
    // pulseseq:s1pul30|sample:|sfrq:500.0887561|sfrq1:125.7466632|solvent:CDCl3|sw:22.0221|swhz:11013|tempfinish:0.0|
    // tempstart:0.0|timefinish:2018-01-09 14:12:12|timestart:2018-01-09 14:08:53|timesubmit:2018-01-09 14:08:53|username:guest|


    public static Map<String, String> paramStr2Map(String paramStr){
        Map<String, String> paramMap = new HashMap<>();
        if(paramStr.startsWith("|")){
            paramStr = paramStr.substring(1);
        }
        if(paramStr.endsWith("|")){
            paramStr = paramStr.substring(0,paramStr.length()-1);
        }
        if(!paramStr.contains("|")){
            log.error("Fail to parse paramStr");
            return null;
        }
        String[] split = paramStr.split("\\|");
        for (String s : split) {
            if(!s.contains(":")){
                log.error("Fail to parse param. param = " + s);
                continue;
            }
            String[] split1 = s.split(":");
            if(split1.length != 2 ){
                log.error("Fail to parse param. param = " + s);
                continue;
            }
            paramMap.put(split1[0], split1[1]);
        }
        return paramMap;
    }

    public static List<ExpParam> paramStr2List (String paramStr){
        List<ExpParam> paramList = new ArrayList<>();
        Map<String, String> paramMap = paramStr2Map(paramStr);
        paramMap.forEach((k, v) -> {
            ExpParam expParam = new ExpParam();
            expParam.setKey(k);
            expParam.setValue(v);
            paramList.add(expParam);
        });
        return paramList;
    }
}
